package com.heima.schedule.service;

import com.alibaba.fastjson.JSON;
import com.heima.common.cache.CacheService;
import com.heima.model.schedule.dto.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Slf4j
public class TaskServiceImpl implements TaskService {

    @Autowired
    private CacheService cacheService;

    @Autowired
    private TaskinfoService taskinfoService;

    @Autowired
    private TaskinfoLogsService taskinfoLogsService;


    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Long addTask(Task task) {

        //校验task
        if (task == null) {
            log.warn("入参不可为空");
            return null;
        }
        //插入taskInfo表
        Taskinfo taskinfo = new Taskinfo();
        BeanUtils.copyProperties(task, taskinfo);
        taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
        boolean taskInfoResult = taskinfoService.save(taskinfo);
        if (!taskInfoResult) {
            log.warn("任务插入失败");
            return null;
        }
        TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
        BeanUtils.copyProperties(taskinfo, taskinfoLogs);
        taskinfoLogs.setExecuteTime(new Date(task.getExecuteTime()));
        taskinfoLogs.setStatus(0);
        boolean taskinfoLogsResult = taskinfoLogsService.save(taskinfoLogs);
        if (!taskinfoLogsResult) {
            log.warn("日志插入失败");
            throw new RuntimeException("日志插入失败");
        }
        //任务执行时间
        long executeTime = task.getExecuteTime();
        //当前时间
        long current = System.currentTimeMillis();
        if (executeTime < current) {
            cacheService.lLeftPush("TOPIC", JSON.toJSONString(task));
        }
        //未来五分钟
        long futureTime = current + (5 * 60 * 1000);
        if(executeTime <= futureTime){
            cacheService.zAdd("FUYURE",JSON.toJSONString(task),executeTime);

        }
        //返回任务id
        return taskinfo.getTaskId();
    }
}
